/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epam.javatanf2013.web.examples.servlets;

import com.epam.javatanf2013.services.CustomerService;
import com.epam.javatanf2013.services.ServiceException;
import com.epam.javatanf2013.services.bo.CustomerBo;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 *
 * @author Istvan_Monori
 */
public class CustomerEditServlet extends HttpServlet {

    @Autowired
    private CustomerService customerService;

    public CustomerService getCustomerService() {
        return customerService;
    }

    public void setCustomerService(CustomerService customerService) {
        this.customerService = customerService;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Logger log = Logger.getLogger(CustomerEditServlet.class.getName());
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String[] params = request.getParameterValues("customer");
            if (params != null) {
                for (String param : params) {
                    out.println(param);
                }
            }

            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Customer Modification</title>");
            out.println("</head>");
            out.println("<body>");

            String param = request.getParameter("id");
            CustomerBo co = new CustomerBo();
            if (param != null) {
                co = getCustomerService().getCustomerById(Integer.valueOf(param));
            }
            out.println("<h1>Customer modification</h1>");

            out.println("<form action=\"" + request.getContextPath() + "/Customer/Edit\" method=\"post\">");
            out.println("<input type=\"hidden\" name=\"customer_id\" value=\"" + co.getId() + "\">");
            out.println("<table>");
            if (request.getAttribute("error.customer.fistname") != null) {
                out.println("<tr>");
                out.println("<td colspan=\"2\">"+request.getAttribute("error.customer.fistname")+"<td>");
                out.println("</tr>");
            }
            out.println("<tr>");
            out.println("<td>First name:</td><td>");
            out.println("<input type=\"text\" name=\"customer_firstname\" value=\"" + co.getFirstName() + "\"/>");
            out.println("</td>");
            out.println("</tr>");
            if (request.getAttribute("error.customer.lastname") != null) {
                out.println("<tr>");
                out.println("<td colspan=\"2\">"+request.getAttribute("error.customer.lastname")+"<td>");
                out.println("</tr>");
            }
            out.println("<tr>");
            out.println("<td>Last name:</td><td>");
            out.println("<input type=\"text\" name=\"customer_lastname\" value=\"" + co.getLastName() + "\"/>");
            out.println("</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>");
            out.println("<a href=\"" + request.getContextPath() + "/Customer\">");
            out.println("Back");
            out.println("</a>");
            out.println("</td>");
            out.println("<td>");
            out.println("<input type=\"submit\" name=\"submit\" value=\"Submit\"/>");
            out.println("</td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("</form>");

            out.println("</body>");
            out.println("</html>");
        } catch (ServiceException ex) {
            log.log(Level.SEVERE, null, ex);
            throw new ServletException(ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Logger log = Logger.getLogger(CustomerEditServlet.class.getName());
        boolean bError = false;
        try {
            if (request.getParameter("customer_firstname")!= null && "".equals(request.getParameter("customer_firstname"))) {
                 request.setAttribute("error.customer.fistname", "Required.");
                 bError = true;
            }
            if (request.getParameter("customer_lastname")!= null && "".equals(request.getParameter("customer_lastname"))) {
                 request.setAttribute("error.customer.lastname", "Required.");
                 bError = true;
            }
            if (request.getParameter("customer_id")== null) {
                 request.setAttribute("error.customer.id", "Required.");
                 bError = true;
            }
            if (!bError) {
                String sId = request.getParameter("customer_id");
                CustomerBo co = null;
                if (!"".equals(sId)) {
                    Integer id = Integer.valueOf(sId);
                    co = getCustomerService().getCustomerById(id);
                } else {
                    co = new CustomerBo();
                }
                /**
                 * @TODO implement missing methods
                 */
                //getCustomerService().saveCustomer(co);
                
                response.sendRedirect(request.getContextPath() + "/Customer");
                return;
            }
            processRequest(request, response);
        }   catch (ServiceException ex) {
            log.log(Level.SEVERE, null, ex);
            throw new ServletException(ex);
        }
    }
            

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Customer Edit Servlet";
    }// </editor-fold>

}
